package com.casic.task;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.List;

/**
 * @author xudezhi
 * @title: SendStateTask
 * @projectName iot-platform
 * @description: TODO
 * @date 2021/4/2713:02:46
 */
@Slf4j
@Component
public class SendStateTask {

    /**
     * restTemplate
     */
    RestTemplate restTemplate=new RestTemplate();

    /**
     * 状态接口信息
     */
    @Autowired
    StateApi stateApi;

    /**
     * 发送测试数据
     */
    @Scheduled(cron = "*/1 * * * * ?") //每秒一次
    public void sendData(){

        /**
         * 生成请求信息
         */
        JSONObject request=new JSONObject();
        request.put("iot",stateApi.iot); //网关
        request.put("accessKey",stateApi.accessKey); //秘钥
        //设备发数情况
        JSONArray data=new JSONArray();

        /**
         * 采集点数据
         */
        List<String> equipments=stateApi.equipment;//采集点名称集合
        for (int i = 0; i < equipments.size(); i++) {
            //发数数据
            JSONObject dataObj=new JSONObject();
            dataObj.put("equipment",equipments.get(i));
            dataObj.put("v", RandomUtil.randomInt(1,8)%4*1000+1000); //生成1000,2000,3000,4000状态随机数
            dataObj.put("t",new Date().getTime());
            data.add(dataObj);
        }
        //发数数据data
        request.put("data",data);
        /**
         * 调用发数接口
         */
        JSONObject result=restTemplate.postForObject(stateApi.url,request,JSONObject.class);//设备发数
        log.info(DateUtil.formatDateTime(new Date())+"发数："+request+"响应："+result);
    }
}
